<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="../jquery/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
	jQuery.fn.maxLength=function(max){
		return this.each(function(){
			var type = this.tagName.toLowerCase();	//获取文本域类型
			var inputType = this.type? this.type.toLowerCase() : null;
			//判断"input"、"text"和"password"文本域类型
			if(type == "input" && inputType == "text" || inputType == "password"){
				this.maxLength = max;
			}else if(type=="textarea"){	//判断"textarea"文本域类型
				this.onkeypress=function(e){	//onkeypress事件处理过程
					var ob=e||event;
					var keyCode=ob.keyCode;	//键盘输入编码
					var hasSelection=document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;	//获取当前页面选中的内容
					return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
				};
				this.onkeyup=function(){	//onkeyup事件处理过程
					if(this.value.length>max){	//判断文本域中字符个数是否大于设定值
						this.value = this.value.substring(0,max);	//截断多余字符
					}
				};
			}
		});
	};
	$("#id-button-maxLen").click(function(){
		var vMaxLen=$('input#id-text-maxLen').val();
		var iMaxLen=parseInt(vMaxLen);
		$('#id-maxLenTextarea').maxLength(iMaxLen);
		$("#div-log").html($("#div-log").html()+"<p>"+"最大输入字符个数设定为:"+vMaxLen+"个"+"</p>");
	});
});
</script>
<title>超实用的jQuery代码段</title>
</head>
<body>
<h2 id="h2-caption">超实用的jQuery代码段 - jQuery如何限制文本域中字符的个数</h2>
<p>
	<b>最大输入字符个数:</b>
	<input type="text" id="id-text-maxLen" style="width:32px;" value="10"/>
</p>
<p>
	<input type="button" id="id-button-maxLen" value="限制文本域中字符的个数"/>
</p>
<div>
	<textarea id="id-maxLenTextarea" name="maxLenTextarea">
	</textarea>
</div>
<div id="div-log">
	<p>日志记录：</p>
</div>
</body>
</html>